package com.yanfan.maintain.controller;

import com.yanfan.attach.domain.DeviceDetail;
import com.yanfan.attach.service.IDeviceDetailService;
import com.yanfan.common.annotation.Log;
import com.yanfan.common.core.controller.BaseController;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.core.domain.entity.SysRole;
import com.yanfan.common.core.domain.model.LoginUser;
import com.yanfan.common.core.page.TableDataInfo;
import com.yanfan.common.enums.BusinessType;
import com.yanfan.energy.domain.*;
import com.yanfan.energy.service.ExcelService;
import com.yanfan.energy.domain.MaintainTasksItems;
import com.yanfan.iot.domain.DeviceLifecyle;
import com.yanfan.maintain.domain.InspectionTask;
import com.yanfan.maintain.domain.ReleaseTask;
import com.yanfan.maintain.service.MaintenancePlanService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 设备保养计划表(MaintenancePlan)表控制层
 *
 * @author makejava
 * @since 2023-03-09 15:01:22
 */
@RestController
@RequestMapping("/maintenancePlan")
@Api(tags = "设备保养计划接口")
public class MaintenancePlanController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private MaintenancePlanService maintenancePlanService;

    /**
     * 下载excel 表格
     */
    @Autowired
    private ExcelService excelService;

    /**
     * 设备详情
     */
    @Autowired
    private IDeviceDetailService deviceDetailService;

    /**
     * 分页查询
     *
     * @param maintenancePlan 筛选条件
     * @return 查询结果
     */
    @PostMapping("/queryByPage")
    public AjaxResult queryByPage(@RequestBody MaintenancePlan maintenancePlan) {
        PageInfo<MaintenancePlan> pageInfo = new PageInfo<>(this.maintenancePlanService.queryByPage(maintenancePlan));
        return AjaxResult.success(pageInfo);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @PostMapping("/queryById/{id}")
    public AjaxResult queryById(@PathVariable("id") Long id) {
        return AjaxResult.success(this.maintenancePlanService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param maintenancePlan 实体
     * @return 新增结果
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody MaintenancePlan maintenancePlan) {
        return AjaxResult.success(this.maintenancePlanService.insert(maintenancePlan));
    }

    /**
     * 编辑数据
     *
     * @param maintenancePlan 实体
     * @return 编辑结果
     */
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody MaintenancePlan maintenancePlan) {
        return AjaxResult.success(this.maintenancePlanService.update(maintenancePlan));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @PostMapping("/deleteById/{id}")
    public AjaxResult deleteById(@PathVariable("id") Long id) {
        return AjaxResult.success(this.maintenancePlanService.deleteById(id));
    }


    /**
     * 设备车间 楼栋下拉框
     *
     * @param baseDictEntity
     * @return
     */
    @PostMapping("/comboBoxLinkage")
    public AjaxResult comboBoxLinkage(@RequestBody BaseDictEntity baseDictEntity) {
        return AjaxResult.success(this.maintenancePlanService.comboBoxLinkage(baseDictEntity));
    }

    /**
     * 任务列表 接口
     *
     * @param maintenancePlan
     * @return
     */
    @PostMapping("/taskListByPlan")
    public AjaxResult taskListByPlan(@RequestBody MaintenancePlan maintenancePlan) {
        PageInfo<MaintainTasks> pageInfo = new PageInfo<>(this.maintenancePlanService.taskListByPlan(maintenancePlan));
        return AjaxResult.success(pageInfo);
    }

    @PostMapping("/planPeriodList")
    public AjaxResult planPeriodList() {
        return AjaxResult.success(this.maintenancePlanService.planPeriodList());
    }

    /**
     * 设备保养计划-计划类型 （定期还是临时）
     *
     * @return
     */
    @PostMapping("/planType")
    public AjaxResult planTypeList() {
        return AjaxResult.success(this.maintenancePlanService.planTypeList());
    }


    /******** ---------------------------------------------保养任务相关接口-------------------------------------- *****/

    /**
     * 保养任务列表查询
     *
     * @param maintainTasks 筛选条件
     * @return 查询结果
     */
    @PostMapping("/queryTaskByPage")
    public AjaxResult queryTaskByPage(@RequestBody MaintainTasks maintainTasks) {
        PageInfo<MaintainTasks> pageInfo = new PageInfo<>(this.maintenancePlanService.queryTaskByPage(maintainTasks));
        return AjaxResult.success(pageInfo);
    }

    /**
     * 任务列表下载
     *
     * @param taskNumber
     * @param taskType
     * @param staffName
     * @param orderNumber
     * @param response
     * @throws IOException
     */
    @PostMapping("/taskListDownload")
    public void taskListDownload(@RequestParam(required = false) String taskNumber, @RequestParam(required = false) String taskType, @RequestParam(required = false) String staffName, @RequestParam(required = false) String orderNumber, HttpServletResponse response) throws IOException {
        MaintainTasks maintainTasks = new MaintainTasks();
        maintainTasks.setTaskNumber(taskNumber);
        maintainTasks.setTaskType(taskType);
        maintainTasks.setStaffName(staffName);
        maintainTasks.setOrderNumber(orderNumber);
        excelService.downloadList(MaintainTasks.class, maintenancePlanService.queryTaskByPage(maintainTasks), response, "保养任务列表");
    }

    /**
     * 保养任务详情
     *
     * @param id 筛选条件
     * @return 查询结果
     */
    @PostMapping("/queryTaskById/{id}")
    public AjaxResult queryTaskById(@PathVariable("id") Long id) {
        return AjaxResult.success(this.maintenancePlanService.queryTaskById(id));
    }

    /**
     * 保养任务新增
     *
     * @param maintainTasks 任务信息
     * @return
     */
    @PostMapping("/taskAdd")
    public AjaxResult taskAdd(@RequestBody MaintainTasks maintainTasks) {
        return AjaxResult.success(this.maintenancePlanService.taskAdd(maintainTasks));
    }

    /**
     * 任务修改
     *
     * @param maintainTasks 任务信息
     * @return
     */
    @PostMapping("/taskEdit")
    public AjaxResult taskEditor(@RequestBody MaintainTasks maintainTasks) {
        return AjaxResult.success(this.maintenancePlanService.taskEdit(maintainTasks));
    }


    /**
     * 保养任务删除
     *
     * @param id 保养任务id
     * @return 查询结果
     */
    @PostMapping("/deleteTaskById/{id}")
    public AjaxResult deleteTaskById(@PathVariable("id") Long id) {
        return AjaxResult.success(this.maintenancePlanService.deleteTaskById(id));
    }


    /**
     * 任务列表 接口
     *
     * @return
     */
    @DeleteMapping("/deleteTaskByIds/{ids}")
    public AjaxResult deleteTask(@PathVariable Long[] ids) {
        return toAjax(this.maintenancePlanService.deleteTaskByIds(ids));
    }

    /**
     * 设备保养顶部接口
     *
     * @param maintainTopRequest
     * @return
     */
    @PostMapping("/maintainTop")
    public AjaxResult maintainTop(@RequestBody MaintainTopRequest maintainTopRequest) {
        return AjaxResult.success(this.maintenancePlanService.maintainTop(maintainTopRequest));
    }

    /******** --------------------------------------------- 保养日常相关接口 -------------------------------------- *****/


    /***
     *  查看某个月的任务
     * @return
     */
    @PostMapping("/showPlansByMonth")
    public AjaxResult showPlansByMonth(@RequestParam(required = true) String yearMonth) {
        return AjaxResult.success(this.maintenancePlanService.showPlansByMonth(yearMonth));
    }

    /***
     *  查看某个月的任务
     * @return
     */
    @PostMapping("/operationCase")
    public AjaxResult operationCase() {
        return AjaxResult.success(this.maintenancePlanService.operationCase());
    }

    /***
     *  查看某个月的任务
     * @return
     */
    @ApiOperation("运维任务信息")
    @PostMapping("/operationCaseNew")
    public AjaxResult operationCaseNew(@RequestBody DeviceChartRequest request) {
        return AjaxResult.success(this.maintenancePlanService.operationCaseNew(request));
    }


    @GetMapping(value = "/statisticNew")
    @ApiOperation("获取设备统计信息")
    public AjaxResult getDeviceStatistic(DeviceChartRequest request) {
        return AjaxResult.success(maintenancePlanService.selectDeviceStatistic(request));
    }

    /***
     *  查看某个月的运维情况
     * @return
     */
    @PostMapping("/deviceDevOps")
    public AjaxResult deviceDevOps(@RequestBody DeviceChartRequest request) {
        return AjaxResult.success(this.maintenancePlanService.deviceDevOps(request));
    }

    /**
     * 设备运维任务
     *
     * @param request
     * @return
     */
    @PostMapping("/devOpsTask")
    public AjaxResult devOpsTask(@RequestBody DevOpsTask request) {
        PageInfo<DevOpsTask> pageInfo = new PageInfo<>(this.maintenancePlanService.devOpsTask(request));
        return AjaxResult.success(pageInfo);
    }

    /**
     * 任务完成
     *
     * @param request
     * @return
     */
    @PostMapping("/devOpsTaskFinish")
    public AjaxResult devOpsTaskFinish(@RequestBody DevOpsTask request) {
        maintenancePlanService.devOpsTaskFinish(request);
        return AjaxResult.success();
    }

    /**
     * 任务开始
     *
     * @param request
     * @return
     */
    @PostMapping("/devOpsTaskStart")
    public AjaxResult devOpsTaskStart(@RequestBody DevOpsTask request) {
        maintenancePlanService.devOpsTaskStart(request);
        return AjaxResult.success();
    }


    /**
     * 处理意见
     *
     * @param request
     * @return
     */
    @PostMapping("/devOpsTaskHandling")
    public AjaxResult devOpsTaskHandling(@RequestBody DevOpsTask request) {
        maintenancePlanService.devOpsTaskHandling(request);
        return AjaxResult.success();
    }


    /**
     * 设备运维任务 分析
     *
     * @param request
     * @return
     */
    @PostMapping("/devOpsAnalyse")
    public AjaxResult devOpsAnalyse(@RequestBody DeviceChartRequest request) {
        return AjaxResult.success(maintenancePlanService.devOpsAnalyse(request));
    }


    /**
     * 设备运维 记录  (保养、维修)
     *
     * @param request
     * @return
     */
    @PostMapping("/devOpsTaskRecord")
    public AjaxResult devOpsTaskRecord(@RequestBody DevOpsTask request) {
        PageInfo<DevOpsTask> pageInfo = new PageInfo<>(this.maintenancePlanService.devOpsTaskRecord(request));
        return AjaxResult.success(pageInfo);
    }


    /**
     * 发布任务  (保养、维修)
     *
     * @param request
     * @return
     */
    @PostMapping("/releaseTask")
    public AjaxResult releaseTask(@RequestBody ReleaseTask request) {
        this.maintenancePlanService.releaseTask(request);
        return AjaxResult.success();
    }


    /**
     * 任务详情
     *
     * @param request
     * @return
     */
    @PostMapping("/devOpsTaskDetails")
    public AjaxResult devOpsTaskDetails(@RequestBody ReleaseTask request) {
        ReleaseTask task = this.maintenancePlanService.devOpsTaskDetails(request);
        return AjaxResult.success(task);
    }

    /**
     * 任务修改
     *
     * @param request
     * @return
     */
    @PostMapping("/devOpsTaskModify")
    public AjaxResult devOpsTaskModify(@RequestBody ReleaseTask request) {
        ReleaseTask task = this.maintenancePlanService.devOpsTaskModify(request);
        return AjaxResult.success(task);
    }


    @GetMapping("/device-newList")
    @ApiOperation("新设备列表")
    public TableDataInfo newListByDevice(DeviceDetail device) {
        startPage();
        return getDataTable(maintenancePlanService.newListByDevice(device));
    }


    @PreAuthorize("@ss.hasPermi('iot:group:list')")
    @GetMapping("/findGroupComboBox")
    @ApiOperation("设备分组（工艺）下拉框")
    public AjaxResult findGroupComboBox() {
        return AjaxResult.success(maintenancePlanService.findGroupComboBox());
    }

    @GetMapping("/findProductComboBox")
    @ApiOperation("产品分页列表")
    public AjaxResult findProductComboBox() {
        return AjaxResult.success(maintenancePlanService.findProductComboBox());
    }


    /**
     * 获取新设备详情
     *
     * @param deviceId
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author caijinkang
     * @date 2023/4/3 16:40
     */
    @ApiOperation("获取新设备详情")
    @GetMapping(value = "/getNewInfo/{deviceId}")
    public AjaxResult getNewInfo(@PathVariable("deviceId") Long deviceId) {
        Map<String, Object> device = maintenancePlanService.selectNewDeviceByDeviceId(deviceId);
        // 判断当前用户是否有设备分享权限 （设备所属机构管理员和设备所属用户有权限）
        LoginUser loginUser = getLoginUser();
        List<SysRole> roles = loginUser.getUser().getRoles();
        // 判断当前用户是否为设备所属机构管理员
        if (roles.stream().anyMatch(a -> "admin".equals(a.getRoleKey()))) {
            device.put("isOwner", 1);
        } else {
            // 判断当前用户是否是设备所属用户
            if (Objects.equals(device.get("tenantId"), loginUser.getUserId())) {
                device.put("isOwner", 1);
            } else {
                device.put("isOwner", 0);
            }
        }
        return AjaxResult.success(device);
    }


    /**
     * 新增设备
     */
    @PreAuthorize("@ss.hasPermi('iot:device:add')")
    @Log(title = "添加设备", businessType = BusinessType.INSERT)
    @PostMapping("saveDevice")
    @ApiOperation("添加设备")
    public AjaxResult saveDevice(@RequestBody DeviceDetail device) {
        return AjaxResult.success(deviceDetailService.insertDeviceDetail(device));
    }


    /**
     * 修改设备
     */
    @PreAuthorize("@ss.hasPermi('iot:device:add')")
    @Log(title = "修改设备", businessType = BusinessType.INSERT)
    @PostMapping("updateDevice")
    @ApiOperation("修改设备")
    public AjaxResult updateDevice(@RequestBody DeviceDetail device) {
        if (device.getDevcieStatus() != 0) {
            List<DeviceLifecyle> deviceLifecyle = maintenancePlanService.getDeviceLifecyle(device.getDeviceId());
            for (DeviceLifecyle lifecyle : deviceLifecyle) {
                if (lifecyle.getDevcieStatus() != device.getDevcieStatus()) {
                    maintenancePlanService.updateDeviceLifecyle(device.getDeviceId(), device.getDevcieStatus());
                    switch (lifecyle.getDevcieStatus()) {
                        case 1:
                        case 2:
                            maintenancePlanService.addMaintainLogs("设备状态已操作为装", device.getDeviceId());
                            break;
                        case 3:
                            maintenancePlanService.addMaintainLogs("设备状态已操作为换", device.getDeviceId());
                            break;
                        case 4:
                            maintenancePlanService.addMaintainLogs("设备状态已操作为拆", device.getDeviceId());
                            break;
                    }
                }
            }
        }
        return AjaxResult.success(deviceDetailService.updateDeviceDetail(device));
    }


    /**
     * 任务列表 接口
     *
     * @return
     */
    @GetMapping("/taskList")
    public TableDataInfo taskList(MaintainTasks tasks) {
        startPage();
        List<MaintainTasks> tasksList = this.maintenancePlanService.taskList(tasks);
        return getDataTable(tasksList);
    }


    /**
     * 保养项目列表 接口
     *
     * @return
     */
    @GetMapping("/taskItemsList")
    public TableDataInfo taskItemsList(MaintainTasksItems tasks) {
        startPage();
        List<MaintainTasksItems> tasksList = this.maintenancePlanService.taskItemsList(tasks);
        return getDataTable(tasksList);
    }

    /**
     * 获取设备保养项目详细信息
     */
    @GetMapping(value = "/taskItems/{id}")
    public AjaxResult getTaskItemsInfo(@PathVariable("id") Long id) {
        return success(maintenancePlanService.selectMaintainTasksItemsById(id));
    }

    /**
     * 新增设备保养项目
     */
    @PostMapping("/taskItemsAdd")
    public AjaxResult addTaskItems(@RequestBody MaintainTasksItems maintainTasksItems) {
        return toAjax(maintenancePlanService.insertMaintainTasksItems(maintainTasksItems));
    }

    /**
     * 修改设备保养项目
     */
    @PutMapping("/taskItemsEdit")
    public AjaxResult editTaskItems(@RequestBody MaintainTasksItems maintainTasksItems) {
        return toAjax(maintenancePlanService.updateMaintainTasksItems(maintainTasksItems));
    }

    /**
     * 删除设备保养项目
     */
    @DeleteMapping("/taskItemsDelete/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(maintenancePlanService.deleteMaintainTasksItemsByIds(ids));
    }


    /**
     * 关联备件图片信息查询
     *
     * @return
     */
    @GetMapping("/maintain-imgs")
    public TableDataInfo maintainImgs(MaintainTasks tasks) {
        List<ImageUrl> list = this.maintenancePlanService.selectMaintainImgs(tasks);
        return getDataTable(list);
    }

    /**
     * 关联设备信息查询
     *
     * @return
     */
    @PostMapping("/maintain-imgs")
    public AjaxResult saveMaintainImgs(@RequestBody MaintainTasks tasks) {
        int i = this.maintenancePlanService.updateMaintainImgs(tasks);
        return toAjax(i);
    }


    /**
     * 关联备件图片信息查询
     *
     * @return
     */
    @GetMapping("/inspection-imgs")
    public TableDataInfo inspectionImgs(InspectionTask tasks) {
        List<ImageUrl> list = this.maintenancePlanService.selectInspectionImgs(tasks);
        return getDataTable(list);
    }

    /**
     * 关联设备信息查询
     *
     * @return
     */
    @PostMapping("/inspection-imgs")
    public AjaxResult saveInspectionImgs(@RequestBody InspectionTask tasks) {
        int i = this.maintenancePlanService.updateInspectionImgs(tasks);
        return toAjax(i);
    }

    @PostMapping("devcioeUpdatelifeCycle")
    @ApiOperation("修改设备基本信息响应")
    public AjaxResult devcioeUpdatelifeCycle(@RequestBody DeviceDetail device) {
        return maintenancePlanService.devcioeUpdatelifeCycle(device);
    }

    @GetMapping("/selectMaintainLogList")
    public TableDataInfo selectMaintainLogList(Long deviceId) {
        startPage();
        return getDataTable(maintenancePlanService.selectMaintainLogList(deviceId));
    }
}

